package com.cong.security.core.code;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cong.security.core.code.sms.SmsCodeSender;
import com.cong.security.core.properties.SecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SmsCodeFilter extends OncePerRequestFilter implements InitializingBean {

    /**
     * 失败处理器
     */
    private AuthenticationFailureHandler myAuthenticationFailureHandler;

    private SmsCodeSender smsCodeSender;

    private UsersConnectionRepository usersConnectionRepository;

    public void setUsersConnectionRepository(UsersConnectionRepository usersConnectionRepository) {
        this.usersConnectionRepository = usersConnectionRepository;
    }

    public void setSmsCodeSender(SmsCodeSender smsCodeSender) {
        this.smsCodeSender = smsCodeSender;
    }

    /**
     * 存放需要拦截的Url
     */
    private Set<String> urls = new HashSet<>();

    private SecurityProperties securityProperties;

    public void setMyAuthenticationFailureHandler(AuthenticationFailureHandler myAuthenticationFailureHandler) {
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String[] configUrls = StringUtils
                .splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getSms().getUrl(), ",");
        for (String string : configUrls) {
            urls.add(string);
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 登录请求才起作用且必须是post请求
        // 判断用户登录请求是否需要先进行验证码校验
        boolean match = false;
        for (String url : urls) {
            if (antPathMatcher.match(url, request.getRequestURI())) {
                match = true;
            }
        }
        // 如果需要进行验证码校验
        if (match) {
            try {
                validate(new ServletWebRequest(request));
            } catch (CodeException e) {
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        // 手机号
        String mobile = ServletRequestUtils.getStringParameter(request.getRequest(), "mobile");
        // 验证码
        String code = ServletRequestUtils.getStringParameter(request.getRequest(), "code");
        // 类型
        String type = ServletRequestUtils.getStringParameter(request.getRequest(), "type");
        // 设备标识
        String deviceId = ServletRequestUtils.getStringParameter(request.getRequest(), "deviceId");
        log.info("[{}]用户输入短信验证码值为[{}]...[{}]...[{}]", mobile, code, type, deviceId);
        if (mobile != null && code != null && type != null && deviceId != null) {
            String test = smsCodeSender.test(usersConnectionRepository, type, mobile, code, deviceId);
            // 用户未输入值
            if (!test.equals("success")) {
                throw new CodeException("短信验证码不匹配");
            }
            // 验证成功，将验证码从session中移除
        } else {
            throw new CodeException("SMS verification code failed to verify");
        }
    }
}